package io.yx.flx.handler.upload;

import cn.hutool.http.Header;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import io.yx.flx.aspect.UploadProxy;
import io.yx.flx.service.UploadService;
import io.yx.flx.service.UploadServiceImpl;
import net.sf.cglib.proxy.Enhancer;

/**
 * 上传带文件名格式
 * {
 * "msg": "success",
 * "code": "0000",
 * "data": [
 * {
 * "fileName": "wallhaven-0pygmp.jpg",
 * "flxUrl": "http://localhost/storage/d5dcf37f-f049-4482-80f3-eccc993027f1.jpg",
 * "url": "http://cdnimg.gpai.net/GPAI5_Compress/2022-01/20220120170231-031-tjqk.jpg"
 * },
 * {
 * "fileName": "wallhaven-2emqoy.jpg",
 * "flxUrl": "http://localhost/storage/bced8e15-0744-4295-8132-d3820a68135e.jpg",
 * "url": "http://cdnimg.gpai.net/GPAI5_Compress/2022-01/20220120170231-031-p9m3.jpg"
 * },
 * {
 * "fileName": "wallhaven-135zr9.jpg",
 * "flxUrl": "http://localhost/storage/51133c2a-d27a-4990-a04d-d909f45b6875.jpg",
 * "url": "http://cdnimg.gpai.net/GPAI5_Compress/2022-01/20220120170233-033-wzus.jpg"
 * }
 * ]
 * }
 */
public class UploadReturnNameHandler implements Handler<RoutingContext> {

    private static final Log log = LogFactory.get();

    private final UploadService uploadService;

    public UploadReturnNameHandler() {

        Enhancer enhancer = new Enhancer();
        // 设置要被代理的类
        enhancer.setSuperclass(UploadServiceImpl.class);
        // 设置回调具体代理的逻辑
        enhancer.setCallback(new UploadProxy());
        enhancer.setClassLoader(UploadServiceImpl.class.getClassLoader());
        // 创建代理类并强制转化为需要的类
        this.uploadService = (UploadServiceImpl) enhancer.create();

    }

    @Override
    public void handle(RoutingContext rc) {
        // 使用代理类执行upload
        try {
            String upload = uploadService.uploadReturnName(rc);
            rc.response().putHeader(Header.CONTENT_TYPE.getValue(), "application/json").end(upload);
        } catch (Exception e) {
            log.error(e);
            throw e;
        }

    }

}
